#include "udpsocket.h"

udpsocket::udpsocket(QObject *parent)
{
    Q_UNUSED(parent);
    connect(this, SIGNAL(readyRead()),
            this, SLOT(processPendingDatagrams()));
}

bool udpsocket::socketBind(quint16 port)
{
    return bind(port, QUdpSocket::ShareAddress);
}

qint64 udpsocket::socketWrite(const QByteArray &datagram, quint16 port)
{

  qint64 wlen = writeDatagram(datagram, QHostAddress::Broadcast, port);
  qDebug() << "socketWrite len = " << wlen << " port = " << port;// << "";
  //    return riteDatagram(datagram, QHostAddress::Broadcast, port);
}

bool udpsocket::hasPending()
{
    return hasPendingDatagrams();
}

QString udpsocket::socketRead()
{
    QByteArray datagram;

    datagram.resize(pendingDatagramSize());
    readDatagram(datagram.data(), datagram.size());

    return QString(datagram);
}

void udpsocket::processPendingDatagrams()
{
    while (hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(pendingDatagramSize());
        //qDebug () << datagram;

        QHostAddress sender;
        quint16 senderPort;

        readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        // messageReceive(QString(datagram));

        //qDebug () << sender.toString();

        emit messageReceive(datagram, sender.toString());
        //dealReceiveData(datagram);
    }
}

void udpsocket::dealReceiveData(const QByteArray &ba)
{
    //qDebug() << ba;
    QByteArray start;
    start.append(0xaa);
    //start.append(0x55);

    QByteArray end;
    end.append(0xcc);
    end.append(0x33);
    end.append(0xc3);
    end.append(0x3c);

    if (!map.contains(ba.at(0)))
      map[ba.at(0)] = ba.mid(1);

    map[ba.at(0)].append(ba.mid(1));
    receiveData = &map[ba.at(0)];

    int startPos = receiveData->indexOf(start);
    int endPos = receiveData->indexOf(end);
    QByteArray cmd;
    while(startPos >= 0 && endPos >=0) {
      int len = endPos - startPos + end.length();
      cmd = receiveData->mid(startPos + start.size(), len - end.size() - start.size());
      //emit messageReceive((ba.at(0)+cmd).toHex());
      //emit messageReceiveInt(QString(cmd.at(0)).toInt());

      //qDebug() << cmd.left(1).toHex();
      //qDebug() << cmd.toHex() << cmd.size() << cmd.toHex().size();
      receiveData->remove(startPos, len);

      startPos = receiveData->indexOf(start);
      endPos = receiveData->indexOf(end);
        //qDebug() << receiveData.length();
    }

}
